/*
 * Copyright 2020 lcnap
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pers.lcnap.simplerpc.rpc.handler;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.lcnap.RpcResponse;
import pers.lcnap.simplerpc.rpc.RpcRequestEvent;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 监听并缓存 {@link RpcRequestEvent}事件。发起请求。并接收{@link RpcResponse},
 * 并通过 RpcRequestId 与请求事件缓存, 调用相关的回调函数。
 *
 * @see RpcRequestQueueChannelHandler
 */
public class RpcCallChannelHandler extends ChannelInboundHandlerAdapter {

    final Logger logger = LoggerFactory.getLogger(RpcCallChannelHandler.class);

    //应该不用管线程安全，但是就这样吧。。
    private ConcurrentHashMap<Long, RpcRequestEvent> requestEvents = new ConcurrentHashMap<>();

    //方便测试
    public void setRequestEvents(ConcurrentHashMap<Long, RpcRequestEvent> requestEvents) {
        this.requestEvents = requestEvents;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof RpcRequestEvent) {
            RpcRequestEvent requestEvent = (RpcRequestEvent) evt;
            requestEvents.put(requestEvent.getRpcRequest().getId(), requestEvent);
            ChannelFuture channelFuture = ctx.writeAndFlush(requestEvent.getRpcRequest());

            channelFuture.addListener(future -> {
                if (!future.isSuccess()) {
                    GenericFutureListener<Future<RpcResponse>> listener = requestEvent.getListener();
                    if(listener != null){
                        listener.operationComplete(ctx.executor().newFailedFuture(future.cause()));
                    }
                } else {
                    logger.debug("send {}",requestEvent.getRpcRequest());
                }
            });
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcResponse response = (RpcResponse) msg;
        RpcRequestEvent requestEvent = requestEvents.remove(response.getRpcRequestId());
        if (requestEvent != null) {
            Future<RpcResponse> future = ctx.executor().newSucceededFuture(response);

            if (response.getException() != null) {
                future = ctx.executor().newFailedFuture(response.getException());
            }
            GenericFutureListener<Future<RpcResponse>> action = requestEvent.getListener();
            if (action != null) {
                action.operationComplete(future);
            }
            logger.debug("received {}",response);
        } else {
            super.channelRead(ctx, msg);
        }

    }
}
